package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2 判断是否是登录
        if (request.getURI().getPath().contains("/login")) {
            //是登录直接放行
           return chain.filter(exchange);
        }
        //3 不是登录.先获取token
        String token = request.getHeaders().getFirst("token");
        //4 判断是否token是否存在
        if (StringUtils.isEmpty(token)) {
            //返回401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 结束方法
            return response.setComplete();
        }
        //5 token存在 解析它
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //5.1 判断是否过期
            int res = AppJwtUtil.verifyToken(claimsBody);
            if (res == 1 || res == 2) {
                //过期
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception e) {
            //token伪造就会抛异常
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //到这就过关了 放行
       return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
